package zq.cn.activity;

import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import util.Globals;
import zq.cn.dao.PageDao;
import zq.cn.dao.TxtDao;
import zq.cn.defview.MyView;

public class MainActivity extends AppCompatActivity {

    private MyView view;
    private TextView tv;
    //文本路径
    private String txtPath;
    //文本信息 txt's infomation
    private Map<String, Object> map;
    //文本详细信息 txt's detail infomation
    private Map<String, Object> pageMap = new HashMap<>();
    private StringBuffer cont = new StringBuffer();
    //当前行
    private int nowLine;
    //当前页数
    private int nowpage = 1;
    //总页数
    private int pageCount = 1;

    //handler实现向页面输出
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Globals.init(this);

        tv = (TextView) findViewById(R.id.reader_nowpage);
        view = (MyView) findViewById(R.id.reader_view);

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                //what==0相当于首次访问，需加载数据，显示分页数据
                if(msg.what==0) {
                    tv.setText("正在读取数据，已读取"+(pageCount-1)+"页");
                }else if(msg.what==1) {
                    tv.setText("第"+nowpage+"/"+pageCount+"页");
                }
            }
        };

        //getAbsolutePath()取得路径为mnt/sdcard
        txtPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sanguo.txt";

        TxtDao.insertTxtInfo(txtPath);

        map = TxtDao.getByPath(txtPath);
        if ((int) map.get("readFlag") == 0) {
            Thread t = new Thread() {
                @Override
                public void run() {
                    //第一次访问，进行分页
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(
                                new FileInputStream(txtPath), "GBK"));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            while (line.length() > Globals.CHARCOUNT_LINE) {
                                String lineSub = line.substring(0, Globals.CHARCOUNT_LINE);
                                line = line.substring(Globals.CHARCOUNT_LINE);

                                addData(lineSub);
                            }
                            //插入最后一行数据
                            addData(line);
                        }
                        br.close();
                        handler.sendEmptyMessage(1);
                        //改变page_tab的readFlag=1,表示数据已经加载
                        TxtDao.updateTxtInfo(txtPath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        } else {
            //直接从上一次的浏览记录开始访问
            pageCount = PageDao.getCountByTxtId((Integer) map.get("txtId"));
            nowpage = (int) map.get("nowPage");
            view.changeData();
        }

    }

    public void addData(String lineSub){
        cont.append(lineSub);
        cont.append(Globals.KEYWORD);
        nowLine++;
        //当满足一页时，插入数据
        if(nowLine==Globals.LINE_COUNT) {
            pageMap.put("txtId", map.get("txtId"));
            pageMap.put("pageNum", pageCount++);
            pageMap.put("content", cont.toString());
            PageDao.insertPageInfo(pageMap);

            if(pageCount==5) {
                view.changeData();
            }
            //在子线程中向页面输出数据，利用Handler实现分页显示
            handler.sendEmptyMessage(0);
            //初始化cont
            cont = new StringBuffer();
            //初始化行
            nowLine=0;
        }
    }

    @Override
    protected void onDestroy() {
        TxtDao.updateNowPage(nowpage,txtPath);
        super.onDestroy();
    }

    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public Map<String, Object> getMap() {
        return map;
    }

    public void setMap(Map<String, Object> map) {
        this.map = map;
    }

    public int getNowpage() {
        return nowpage;
    }

    public void setNowpage(int nowpage) {
        this.nowpage = nowpage;
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }
}
